package com.example.servicedemo.views;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import com.example.servicedemo.R;


public class ClientActivity extends AppCompatActivity implements View.OnClickListener {
    private Messenger mServiceMessenger; // 服务端的Messenger
    private boolean isBound;
    private EditText mInput;
    private Button mSend;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client);
        // 绑定服务
        Intent intent = new Intent();
        intent.setAction("com.jn.messenger.service");
        // 跨应用时需指定服务端包名
        intent.setPackage("com.jn.servicedemo"); // 服务端应用包名
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        mSend = findViewById(R.id.send);
        mInput = findViewById(R.id.input);
        mSend.setOnClickListener(this);

    }

    // 服务连接回调
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d("asdf", "onServiceConnected");
            // 1. 通过服务端的Binder创建Messenger
            mServiceMessenger = new Messenger(service);
            isBound = true;
            // 连接成功后发送消息
            sendMessageToService("hello");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mServiceMessenger = null;
            isBound = false;
        }
    };

    // 发送消息到服务端
    private void sendMessageToService(String msg) {
        if (!isBound) return;

        // 2. 创建消息1：传递字符串
        Message msg1 = Message.obtain(null, 1); // what=1 标识消息类型
        Bundle bundle = new Bundle();
        bundle.putString("content", msg);
        msg1.setData(bundle);

        // 3. 创建消息2：传递int值（通过arg1）
        Message msg2 = Message.obtain(null, 2, msg.length(), 0); // what=2，arg1=100

        try {
            // 4. 发送消息
            mServiceMessenger.send(msg1);
            mServiceMessenger.send(msg2);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isBound) {
            unbindService(mConnection);
            isBound = false;
        }
    }

    @Override
    public void onClick(View v) {
        String msg = mInput.getText().toString();
        sendMessageToService(msg);
        mInput.setText("");
    }
}